package com.pc.service;

import com.pc.mapper.SysPermissionMapper;
import com.pc.mapper.SysRoleMapper;
import com.pc.mapper.UserAccountMapper;
import com.pc.pojo.AuthUser;
import com.pc.pojo.SysPermission;
import com.pc.pojo.SysRole;
import com.pc.pojo.UserAccount;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

// CustomUserDetailsService.java
@Service
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        UserAccount userAccount = userAccountMapper.selectByUsername(username);
        if (userAccount == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        if (userAccount.getStatus() == 0) {
            throw new RuntimeException("用户已被禁用");
        }

        // 查询用户角色
        List<SysRole> roles = sysRoleMapper.selectRolesByUserId(userAccount.getUserId());

        // 查询用户权限
        List<SysPermission> permissions = sysPermissionMapper.selectPermissionsByUserId(userAccount.getUserId());

        // 构建权限列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (SysRole role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }
        for (SysPermission permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission.getPermName()));
        }

        return new AuthUser(
                userAccount.getUserId(),
                userAccount.getUsername(),
                userAccount.getPassword(),
                authorities,
                userAccount.getStatus() == 1
        );
    }
}
